<?php

namespace app\common\service;

use app\common\lib\Qiniu;

class Upload
{

    public function upload(){
        if (empty($_FILES['file'])) {
            return show(config('status.error_code'), '您提交的图片数据不合法', '您提交的图片数据不合法');
        }
        $Qiniu = new Qiniu();

        $upload = $Qiniu->postDoupload($_FILES['file']);

        if($upload['status'] == 'fail'){
            return show(config('status.error_code'), $upload['message'], $upload['message']);
        }

        $imgurl = config('qiniu.image_url') . $upload['key'];

        return show(config('status.success_code'), 'ok', $imgurl);
    }

    public function layuiUpload()
    {
        if (empty($_FILES['file'])) {
            return show(config('status.error_code'), '您提交的图片数据不合法', '您提交的图片数据不合法');
        }
        $Qiniu = new Qiniu();

        $upload = $Qiniu->postDoupload($_FILES['file']);

        if ($upload['status'] == 'fail') {
            return json([
                'code' => 101,
                'msg' => 'Error',
            ]);
        }

        $imgurl = config('qiniu.image_url') . $upload['key'];

        return json([
            'code' => 0,
            'msg' => 'Success',
            'data' => [
                'src' => $imgurl, // 图片路径
                'title' => '' // 图片名称，可选
            ]
        ]);
    }

    public function uploadstream($data){
        $Qiniu = new Qiniu();
        $upload = $Qiniu->ResumeUpload($data);
        if($upload['status'] == 'fail'){
            return show(config('status.error_code'), $upload['message'], $upload['message']);
        }
        $imgurl = config('qiniu.image_url') . $upload['key'];

        return $imgurl;
    }

    public function delete($imgUrl){
        //$id = $param->imgId;
        $url = $imgUrl;
        $key = substr(strrchr($url, '/'), 1);
        $Qiniu = new Qiniu();
        // 删除七牛图片
        $result = $Qiniu->delImg($key);
        if($result == NULL){
            return show(config('status.SUCCESS_STATUS'), '删除成功', '删除成功！');
        }else{
            return show(config('status.ERROR_STATUS'), '删除失败', '删除失败！');
        }
    }
}